package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URISyntaxException;

/**
 * 1:定义一个注解:@AutoRunMethod
 * 2:随机为Person,Student,Teacher中的方法添加该注解
 * 3:调用与当前类Test6中所有被@AutoRunClass标注的类中那些被@AutoRunMethod标注的方法
 */
public class Tets6 {
    public static void main(String[] args) throws Exception {
        File file=new File(
                Tets6.class.getResource(".").toURI()
        );
        File[] subs=file.listFiles(f->f.getName().endsWith(".class"));
        for (File sub:subs){
            String fileName=sub.getName();
            String className=fileName.substring(0,fileName.indexOf("."));
            String packName=Tets6.class.getPackage().getName();
            String a=packName+"."+className;
            Class cls=Class.forName(a);
            //查看该类是否被注解@AutoRunClass标注了?
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj=cls.newInstance();
                Method[] methods=cls.getDeclaredMethods();
                for (Method m:methods){
                    //判断是否被注解@AutoRunMethod标注
                    if (m.isAnnotationPresent(AutoRunMethod.class)){
                        /*
                            补充,获取到该注解的参数,根据参数来解决调用该方法的参数
                         */
                        AutoRunMethod arm=m.getAnnotation(AutoRunMethod.class);
                        int value= arm.value();
                        for (int i = 1; i <=value; i++) {
                            m.invoke(obj);
                        }
                    }
                }
            }
        }
    }
}
